<template>
  <div class="cart">
    <header>
      <van-nav-bar
      title="购物车"
      @click-left="$router.back()"
      left-arrow>
        <template #right>
          <p><span>配送至宝山区吴淞街道</span><van-icon name="arrow-down" /><b>预计11月3日(周二)送达</b></p>
        </template>
      </van-nav-bar>
    </header>
    <div class="content">
      <div class="fuwu">
        <p>
          <van-icon name="like-o" /><span>正品</span>
        </p>
        <p>
          <van-icon name="like-o" /><span>正品</span>
        </p>
        <p>
          <van-icon name="like-o" /><span>正品</span>
        </p>
      </div>
      <div class="">
        <van-empty description="购物车里空空如也" v-if="flag">
          <van-button round type="danger" class="bottom-button" @click="$router.push('/index')">
            去逛逛
          </van-button>
        </van-empty>
        <div class="" v-else>
          <!-- 获取索引，便于删除按钮传入索引 -->
          <van-swipe-cell v-for="(item, index) in cartList" :key="item.proId">
            <van-card
              :price="item.price"
              :title="item.proName"
              class="goods-card"
              :thumb="item.proImg"
            >
             <template #thumb>
               <van-checkbox v-model="item.flag" @click="selFlag(index)"></van-checkbox>
               <van-image :src="item.mainImg" fit="cover" />
             </template>
             <template #num>
              <van-stepper v-model="item.num" theme="round" button-size="22" @change="change" :name="item.proId" />
             </template>
            </van-card>
            <template #right>
              <!-- 接收索引，便于删除后不需要刷新页面就可以删除dom元素 -->
              <van-button square text="删除" type="danger" class="delete-button" @click="del(item.proId, index)" />
            </template>
          </van-swipe-cell>
          <van-submit-bar :price="priceSum * 100" button-text="提交订单" @submit="onSubmit">
            <van-checkbox v-model="allSeltFlag">全选</van-checkbox>
            <template #tip>
              您选择了<span style="font-size:24px">{{pronumSum}}</span>件商品
            </template>
          </van-submit-bar>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Icon, Cell, CellGroup, SwipeCell, Card, Button, Empty, Stepper, SubmitBar, Checkbox, Image as VanImage } from 'vant'
import { getCart, getDetail, updateCartNum, delCart, updateFlag, updateAllFlag, addOrder } from '../../api/index.js'


Vue.use(NavBar)
Vue.use(Icon)
Vue.use(Cell)
Vue.use(CellGroup)
Vue.use(SwipeCell)
Vue.use(Card)
Vue.use(Button)
Vue.use(Empty)
Vue.use(Stepper)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(VanImage)

export default {
    data () {
    return {
      cartList: [],
      show: false
    }
  },
  // beforeRouteEnter (to, from, next) {
  //   next((vm) => {
  //     if (vm.isLogin === 'ok') {
  //       next()
  //     } else {
  //       // 设置登录后在哪个页面
  //       next('/login?path=' + to.path)
  //     }
  //   })
  // },
  methods: {
    change (val, detail) {
      // console.log(val, detail)
      updateCartNum({
        userId: localStorage.getItem('userId'),
        proId: detail.name,
        num: val
      }).then((res) => {
        // console.log(res)
      })
    },
    del (proId, i) {
      delCart({
        userId: localStorage.getItem('userId'),
        proId: proId
      }).then((res) => {
        // console.log(res)
        this.cartList.splice(i, 1)
      })
    },
    onSubmit () {
      const arr = this.cartList.filter((val) => {
        return val.flag === true
      })
      // 处理数据，把不需要的剔除掉
      addOrder({
        userId: localStorage.getItem('userId'),
        proData: arr
      }).then((res) => {
        console.log('添加订单成功')
        this.$router.push('/order?active=1')
      })
    },
    selFlag (i) {
      // console.log(this.cartList[i].proId, this.cartList[i].flag)
      updateFlag({
        userId: localStorage.getItem('userId'),
        proId: this.cartList[i].proId,
        flag: this.cartList[i].flag
      }).then((res) => {
        // console.log(res)
      })
    },
    rightNav () {
      this.show = !this.show
    }
  },
  mounted () {
    getCart({
      userId: localStorage.getItem('userId')
    }).then((res) => {

      if (res.data.state === 200) {
        // this.cartList = res.data.data.proData
        const arr = res.data.data.proData
        arr.forEach(element => {
          getDetail({
            id: element.proId
          }).then((data) => {
            const obj = data.data.data[0]
            obj.num = element.num
            obj.time = element.time + ''
            obj.flag = element.flag
            this.cartList.push(obj)
            console.log(this.cartList)
          })
        })
      } else {
        console.log('没有数据，购物车空空如也')
      }
    })
    document.addEventListener('click', () => {
      this.show = false
    })
  },
  computed: {
    // 利用计算属性,根据数据的长度,实现空购物车和列表的切换
    flag () {
      // 长度小于1时返回true,flag=true时,空页面显示,大于0时返回false,flag=false,购物车有数据的页面显示
      return this.cartList.length < 1
    },
    pronumSum () {
      // 利用数组的reduce的特点求数组的和,prev是指定初始值或者上一次返回的值
      return this.cartList.reduce((prev, next) => {
        if (next.flag) {
          return prev + (next.num - 0)
        } else {
          return prev
        }
      }, 0)
    },
    priceSum () {
      return this.cartList.reduce((prev, next) => {
        if (next.flag) {
          return prev + (next.num - 0) * next.price
        } else {
          return prev
        }
      }, 0)
    },
    // 计算全选效果
    allSeltFlag: {
      // 通过选中单个商品决定是否选中全选框
      get () {
        return this.cartList.every((val) => {
          // 返回val的flag啥意思
          return val.flag
        })
      },
      set (v) {
        // 把商品列表的所有复选框的状态设置的和全选复选框的状态一样
        for (let i = 0; i < this.cartList.length; i++) {
          this.cartList[i].flag = v
        }
        updateAllFlag({
          userId: localStorage.getItem('userId'),
          flag: v
        }).then((res) => {
          // console.log('全部状态更新成功')
        })
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.cart ::v-deep .van-nav-bar{
      background: #f23869;
      padding: 0 0 25px 0;
      &::after{
        border-bottom-width: 0;
      }
      .van-nav-bar__left{
        top: -23px;
        .van-icon{
          color: white;
          font-size: 24px;
        }
      }
      .van-nav-bar__title{
        color: white;
        margin-left: 50px;
        font-size: 25px;
      }
      .van-nav-bar__right{
        p{
          position: absolute;
          bottom: 12px;
          left: -295px;
          z-index: 2;
          font-size: 13px;
          color: white;
          i{
            // border: 1px solid black;
            margin: 0 5px;
            padding: 3px;
            background: #e8e8e8;
            border-radius: 50%;
            opacity: 0.4;
          }
        }
      }
}
.cart ::v-deep .van-card__thumb{
  display: flex;
  width: 1.2rem;
  img{
    width: 88px;
  }
}
.delete-button {
    height: 100%;
  }
.cart{
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
  header{
    position: relative;
  }
  .content{
    margin-top: -2px;
    flex: 1;
    overflow: auto;
    .fuwu{
      display: flex;
      justify-content: space-around;
      background: #f23869;
      height: 30px;
      margin-bottom: 20px;
      span{
        padding-left: 10px;
        color: #aaaaaa;
      }
      .van-icon{
        color: white;
      }
    }
    .van-card{
      font-size: 16px;
    }
  }
} 
</style>